package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.web.admin.context.LoginUserContext;
import com.atguigu.lease.web.admin.service.SystemUserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    //该方法不放行，handler不执行，即轮不到controller执行 true放行 false拦截
    @Autowired
    private SystemUserService systemUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("access_token");
        //检查用户发送过来的请求中是否携带token
        if(!StringUtils.hasLength(token)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }
        //解析用户携带的token获得用户useId 用于登陆后页面显示 姓名和头像图片
        Long userId = JwtUtil.parseToken(token);
        SystemUser systemUser = systemUserService.getById(userId);
        //将systemUser对象放进线程中
        LoginUserContext.setUser(systemUser);
        return true;
    }

    //业务代码执行完成之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    //视图解析器调用之后执行，该方法执行后进程离开springmvc框架
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.remove();
    }
}
